import Vue from 'vue';
import VueRouter from 'vue-router';
import {routers} from './router';
import iView from 'iview';
import Util from '../lib/util';
import Cookies from 'js-cookie'
import { appRouters,otherRouters} from './router'
import Jquery from 'jquery'

Vue.use(VueRouter);

const RouterConfig = {
    // mode: 'history',
    routes: routers
};

export const router = new VueRouter(RouterConfig);

router.beforeEach((to, from, next) => {
    iView.LoadingBar.start();
    Util.title(to.meta.title);

    Jquery('#index-container').scrollTop(0);

    var isLogined = Util.abp.session.userId != null && sessionStorage.getItem('userType') == 'member';
    
    if (!isLogined && to.path.match("/member/")) {
        next({
            name: 'login'
        });
    } else if(isLogined && to.name == 'login') {
        next({
            name: 'member-index'
        });
    } else {
        const curRouterObj = Util.getRouterObjByName([otherRouters, ...appRouters], to.name);
        if (curRouterObj && curRouterObj.permission) {
            if (window.abp.auth.hasPermission(curRouterObj.permission)) {
                Util.toDefaultPage([otherRouters, ...appRouters], to.name, router, next);
            } else {
                next({
                    replace: true,
                    name: 'error-403'
                });
            }
        } else {
            Util.toDefaultPage([...routers], to.name, router, next);
        }
    }
});
router.afterEach((to) => {
    Util.openNewPage(router.app, to.name, to.params, to.query);
    iView.LoadingBar.finish();
});